//
//  HYTableViewSection.m
//
//  Created by yan on 2017/5/8.
//  Copyright © 2017年 yan. All rights reserved.
//

#import "HYTableViewSection.h"

@implementation HYTableViewSection

- (void)addRowModel:(HYTableViewRow *)model atSection:(NSUInteger)section {
    @synchronized (self) {
        if (section == self.sections.count) {
            [self.sections addObject:[NSMutableArray array]];
        }
        NSMutableArray *array = self.sections[section];
        [array addObject:model];
    }
}

- (void)addRowModels:(NSArray<HYTableViewRow *> *)models atSection:(NSUInteger)section {
    @synchronized (self) {
        if (section == self.sections.count) {
            [self.sections addObject:[NSMutableArray array]];
        }
        NSMutableArray *array = self.sections[section];
        [array addObjectsFromArray:models];
    }
}

- (void)insertSectionWithModels:(NSArray<HYTableViewRow *> *)models atIndex:(NSUInteger)index {
    @synchronized (self) {
        if (index == self.sections.count) {
            [self addRowModels:models atSection:index];
        } else {
            NSMutableArray *array = [NSMutableArray arrayWithArray:models];
            [self.sections insertObject:array atIndex:index];
        }
    }
}

- (void)insertRowModel:(HYTableViewRow *)model atIndexPath:(NSIndexPath *)indexPath {
    @synchronized (self) {
        NSMutableArray *array = self.sections[indexPath.section];
        [array insertObject:model atIndex:indexPath.row];
    }
}

- (void)removeRow:(NSUInteger)row AtSection:(NSUInteger)section {
    @synchronized (self) {
        NSMutableArray *array = self.sections[section];
        [array removeObjectAtIndex:row];
    }
}

- (void)removeSection:(NSUInteger)section {
    @synchronized (self) {
        [self.sections removeObjectAtIndex:section];
    }
}

- (id)modelAtIndexPath:(NSIndexPath *)indexPath {
    NSMutableArray *array = self.sections[indexPath.section];
    return array[indexPath.row];
}

- (NSUInteger)numberOfSections {
    return self.sections.count;
}

- (NSUInteger)numberOfRowsInSection:(NSUInteger)section {
    NSMutableArray *array = self.sections[section];
    return array.count;
}

- (NSMutableArray *)sections {
    if (!_sections) {
        _sections = [NSMutableArray array];
    }
    return _sections;
}

@end


